package com.kingdee.pda.ui.scan_inwarehouse;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.basecommon.utils.MusicUtils;
import com.example.basecommon.utils.PreferencesUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.ScanSnResponsebean;
import com.kingdee.pda.entity.SnlistBean;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.activity.QueryLocationStockActivity;
import com.kingdee.pda.ui.out_check.OutCheckActivity;
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow;
import com.kingdee.pda.ui.scan_inwarehouse.ScanReceiveOrderBean.AsnListBean.DetailBean;
import com.kingdee.pda.util.CommonUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 扫描收货操作界面
 * * Created by dlj
 * DATE 2021/11/8
 * TIME 10:20
 */
public class ScanReceiveOperationActivity extends BaseTitleActivity implements View.OnKeyListener, ScanReceiveContract.IScanReceiveView {
    @BindView(R.id.et_skuCode)
    EditText et_skuCode;
    @BindView(R.id.et_owner)
    EditText et_owner;
    @BindView(R.id.et_receiveNum)
    EditText et_receiveNum;
    @BindView(R.id.ll_owner)
    LinearLayout ll_owner;

    @BindView(R.id.tv_asnOrderNo)
    TextView tv_asnOrderNo;
    @BindView(R.id.tv_spuName)
    TextView tv_spuName;
    @BindView(R.id.tv_spuCode)
    TextView tv_spuCode;
    @BindView(R.id.tv_skuName)
    TextView tv_skuName;
    @BindView(R.id.tv_planNum)
    TextView tv_planNum;

    @BindView(R.id.btn_confirm)
    Button btn_confirm;

    @BindView(R.id.et_sn)
    EditText et_sn;

    @BindView(R.id.et_sn_view)
    LinearLayout et_sn_view;

    private List<ScanReceiveShowDetailBean> detailBeans;//整个快递单/ASN单所有的详情（合并后）
    private List<ScanReceiveShowDetailBean> scanSkuDetailBeans = new ArrayList<>();//扫描sku之后过滤得到的sku列表（不同货主）
    private ScanReceiveShowDetailBean selectedDetailbean;//选中的 sku+货主 对应的sku详情
    private boolean autoSn;//整个仓库是否开启全局sn权限
    private ScanSnResponsebean scanSnResponsebean;
    private ScanReceivePresenter scanReceivePresenter;
    private List<ScanReceiveOrderBean.AsnLinkAfterOrderSnVo> linkAfterOrderSnList;//销售出库单中，用来判断扫描的sn是否为该仓库出售
    private boolean isSingle;
    private String typein;
    private boolean snboolean;
    private long scanSnTime = 0;

    public static void actionStart(Context context, List<ScanReceiveShowDetailBean> detailBeans, List<ScanReceiveOrderBean.AsnLinkAfterOrderSnVo> linkAfterOrderSnList, boolean isSingle, String typein, boolean snboolean) {
        Intent intent = new Intent(context, ScanReceiveOperationActivity.class);
        intent.putExtra("detailBeans", (Serializable) detailBeans);
        intent.putExtra("linkAfterOrderSnList", (Serializable) linkAfterOrderSnList);
        intent.putExtra("isSingle", isSingle);
        intent.putExtra("typein", typein);
        intent.putExtra("snboolean", snboolean);

        context.startActivity(intent);
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {

    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_receive_operation);

    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("扫描收货");

        setEditTextScannerEvents(et_skuCode, this);
        setEditTextScannerEvents(et_receiveNum, this);
        setEditTextScannerEvents(et_sn, this);

    }

    @Override
    protected void initData() {
        super.initData();
        detailBeans = (List<ScanReceiveShowDetailBean>) getIntent().getSerializableExtra("detailBeans");
        linkAfterOrderSnList = (List<ScanReceiveOrderBean.AsnLinkAfterOrderSnVo>) getIntent().getSerializableExtra("linkAfterOrderSnList");
        isSingle = getIntent().getBooleanExtra("isSingle", false);
        typein = getIntent().getStringExtra("typein");
        snboolean = getIntent().getBooleanExtra("snboolean", false);

//        autoSn = PreferencesUtils.getBoolean(this, "autoSn");
        scanReceivePresenter = new ScanReceivePresenter(this, this);

    }

    @OnClick({R.id.btn_detail, R.id.btn_confirm, R.id.iv_owner_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_owner_select:
                showOwnerSelector();
                break;
            case R.id.btn_detail:
                ScanReceiveDetailActivity.actionStart(ScanReceiveOperationActivity.this, detailBeans);
                break;
            case R.id.btn_confirm:
                HashMap<String, List<DetailBean>> asnMergeMap = new HashMap<>();//提交之前先根据单号合并所有详情
                for (ScanReceiveShowDetailBean showDetailBean : detailBeans) {
                    for (DetailBean detailBean : showDetailBean.getDetailBeanList()) {
                        List<SnlistBean> snlist = new ArrayList<>();
                        snlist.addAll(showDetailBean.getSnlist());
                        detailBean.setSnlist(snlist);
                        List<DetailBean> detailBeans;
                        if (asnMergeMap.containsKey(detailBean.getScanbillno())) {
                            detailBeans = asnMergeMap.get(detailBean.getScanbillno());
                        } else {
                            detailBeans = new ArrayList<>();
                        }
                        detailBeans.add(detailBean);
                        asnMergeMap.put(detailBean.getScanbillno(), detailBeans);
                    }
                }

                //遍历合并的map，拼接后台参数
                List<ScanReceiveOrderBean.AsnListBean> asnListBeans = new ArrayList<>();
                Set<String> asnOrders = asnMergeMap.keySet();
                for (String asnOrder : asnOrders) {
                    List<DetailBean> detailBeans = asnMergeMap.get(asnOrder);
                    ScanReceiveOrderBean.AsnListBean asnListBean = new ScanReceiveOrderBean.AsnListBean();
                    asnListBean.setType("1");
                    asnListBean.setScanbillno(detailBeans.get(0).getScanbillno());
                    asnListBean.setId(detailBeans.get(0).getId());
                    asnListBean.setDetail(detailBeans);
                    asnListBeans.add(asnListBean);
                }

                scanReceivePresenter.confirmReceipt(asnListBeans);
                break;
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input)) return true;
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            if (v.getId() == R.id.et_skuCode) {
                MusicUtils.getInstance().playSuccess(2);
                //好太太特殊处理
                if (input.length() >= 22 && detailBeans.size() > 0 && "广东好太太科技集团股份有限公司".equals(detailBeans.get(0).getOwnername())) {  //好太太需要截取22位
                    input = input.substring(0, 22);
                }
                String skuSplit = CommonUtil.skuCodeSplit(ScanReceiveOperationActivity.this, input);
                if (TextUtils.isEmpty(skuSplit)) {
//                    if (snboolean && isContainsLinkAfterOrderSnList(input)) {
                    if (snboolean) {
                        scanReceivePresenter.pdaSnScan(input);
                    } else {
                        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                        CommonUtil.requestFocusAndNoClearText(et_skuCode);
                    }
                    return false;
                }
                //扫描sku之后去查询详情里面是否有符合的
                scanSkuDetailBeans.clear();

                for (ScanReceiveShowDetailBean bean : detailBeans) {
                    // 匹配条码
                    if (bean.getSkubarcode().contains(skuSplit)) {
                        scanSkuDetailBeans.add(bean);
                    }
                }

                if (scanSkuDetailBeans.size() > 0) {
                    //扫描商品后，默认选中第一个货主
                    selectedDetailbean = scanSkuDetailBeans.get(0);

                    et_owner.setText(selectedDetailbean.getOwnername());
                    //刷新界面
                    reflushTextView();
                    et_skuCode.setText(skuSplit);

                    // 获取商品的类型
                    boolean skuSingle = false;
                    switch (getSnType(selectedDetailbean)) {
                        case "ALL":
                            // 全程
                            if (!"采购入库".equals(typein)) {
                                SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "非采购入库必须扫S序列号！", true, false);
                                CommonUtil.requestFocusAndClearText(et_skuCode);
                                selectedDetailbean = null;
                            } else {
                                // 采集唯一码
                                et_sn_view.setVisibility(View.VISIBLE);
                                CommonUtil.requestFocusAndClearText(et_sn);
                            }
                            return true;
                        case "OFF":
                        case "HALF":
                            break;
                        default:
                            SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "商品唯一码类型不存在！", true, false);
                            CommonUtil.requestFocusAndClearText(et_skuCode);
                            selectedDetailbean = null;
                            return true;
                    }

                    addData(isSingle || skuSingle);
                } else if (snboolean && isContainsLinkAfterOrderSnList(input)) {//如果扫描的条码没有找到，并且仓库sn权限开启，并且属于该仓库出售sn，则需要去调用sn查询的接口
                    scanReceivePresenter.pdaSnScan(input);
                } else {//否则的话就是扫错了
                    SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "商品条码/SN码扫描有误，请检查", true, false);
                    selectedDetailbean = null;
                    et_owner.setText("");
                    reflushTextView();
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                }
                return true;
            } else if (v.getId() == R.id.et_receiveNum) {
                if (selectedDetailbean == null) {
                    SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "请先输入商品条码并确认", true, false);
                } else {
                    int inputQty = Integer.parseInt(input);
                    int totalQty = selectedDetailbean.getScannedqty() + inputQty;
                    if (totalQty > (selectedDetailbean.getPalnqty() - selectedDetailbean.getReceiptedqty())) {//数量不能超收
                        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "收货数量不能超收", true, false);
                        CommonUtil.requestFocusAndClearText(et_receiveNum);
                    } else {
                        selectedDetailbean.setScannedqty(totalQty);
                        tv_planNum.setText(selectedDetailbean.getScannedqty() + "/" + (selectedDetailbean.getPalnqty() - selectedDetailbean.getReceiptedqty()));
                        btn_confirm.setEnabled(true);
                        //总数量增加之后，再对该sku对应的多条详情进行数量分配
                        for (DetailBean detailbean : selectedDetailbean.getDetailBeanList()) {
                            int leftQty = detailbean.getPalnqty() - detailbean.getReceiptedqty() - detailbean.getScannedqty();
                            if (inputQty > 0 && leftQty > 0) {//如果这条明细没分完
                                if (inputQty > leftQty) {//并且扫描的数量大于此条明细的待收数量，此条明细直接收满
                                    inputQty -= leftQty;
                                    detailbean.setScannedqty(detailbean.getPalnqty() - detailbean.getReceiptedqty());
                                } else {
                                    detailbean.setScannedqty(detailbean.getScannedqty() + inputQty);
                                    inputQty = 0;
                                }
                            }
                        }
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                    }
                }
            } else if (v.getId() == R.id.et_sn) {
                if(System.currentTimeMillis() - scanSnTime < 2000 ) {
                    return true;
                }
                scanSnTime = System.currentTimeMillis();
                scanReceivePresenter.pdaCollectNullSn(input);
                return true;
            }
        }
        return false;
    }

    private String getSnType(ScanReceiveShowDetailBean showDetailBean) {
        if (!snboolean) {
            return "OFF";
        }
        return showDetailBean.getSn();
    }

    private void addData(boolean single) {
        if (single) {
            // 逐件处理
            int totalQty = selectedDetailbean.getScannedqty() + 1;
            if (totalQty > (selectedDetailbean.getPalnqty() - selectedDetailbean.getReceiptedqty())) {//数量不能超收
                SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "收货数量不能超收", true, false);
                CommonUtil.requestFocusAndClearText(et_skuCode);
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(et_skuCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                selectedDetailbean.setScannedqty(totalQty);
                tv_planNum.setText(selectedDetailbean.getScannedqty() + "/" + (selectedDetailbean.getPalnqty() - selectedDetailbean.getReceiptedqty()));
                btn_confirm.setEnabled(true);
                //总数量增加之后，再对该sku对应的多条详情进行数量分配
                for (DetailBean detailbean : selectedDetailbean.getDetailBeanList()) {
                    int leftQty = detailbean.getPalnqty() - detailbean.getReceiptedqty() - detailbean.getScannedqty();
                    if (leftQty > 0) {//如果这条明细没分完
                        detailbean.setScannedqty(detailbean.getScannedqty() + 1);
                        break;
                    }
                }
                CommonUtil.requestFocusAndClearText(et_skuCode);
            }
        } else {
            CommonUtil.requestFocusAndClearText(et_receiveNum);
        }
    }

    /**
     * 判断扫描的sn是否为该仓库销售出去的，是的话再去查询该sn的状态
     *
     * @param inputSn
     * @return
     */
    private boolean isContainsLinkAfterOrderSnList(String inputSn) {
        //如果此集合为空，则不需要判断直接返回true
        if (linkAfterOrderSnList.size() == 0) return true;
        for (ScanReceiveOrderBean.AsnLinkAfterOrderSnVo bean : linkAfterOrderSnList) {
            if (inputSn.equals(bean.getSncode())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 展示货主选择框
     */
    private void showOwnerSelector() {
        ListSelectorPpWindow<ScanReceiveShowDetailBean> locationSelector = new ListSelectorPpWindow<>(ScanReceiveOperationActivity.this,
                R.drawable.shape_bg_edit_selected,
                ll_owner.getWidth(),
                scanSkuDetailBeans, new ListSelectorPpWindow.onItemSelectedListener() {
            @Override
            public void onItemSelected(Object item) {
                selectedDetailbean = (ScanReceiveShowDetailBean) item;
                reflushTextView();
                CommonUtil.requestFocusAndClearText(et_receiveNum);
            }
        });
        locationSelector.showAsDropDown(ll_owner, 0, 10);
    }

    private void reflushTextView() {
        et_owner.setText(selectedDetailbean == null ? "" : selectedDetailbean.getOwnername());
        tv_asnOrderNo.setText(selectedDetailbean == null ? "" : selectedDetailbean.getBillnos().toString().replace("[", "").replace("]", ""));
        tv_spuName.setText(selectedDetailbean == null ? "" : selectedDetailbean.getSpuname());
        tv_spuCode.setText(selectedDetailbean == null ? "" : selectedDetailbean.getSkubarcode().toString().replace("[", "").replace("]", ""));
        tv_skuName.setText(selectedDetailbean == null ? "" : selectedDetailbean.getSkuname());
        tv_planNum.setText(selectedDetailbean == null ? "" : selectedDetailbean.getScannedqty() + "/" + (selectedDetailbean.getPalnqty() - selectedDetailbean.getReceiptedqty()));
    }

    @Override
    public void pdaSnScanSuccess(ScanSnResponsebean responsebean) {
        scanSnResponsebean = responsebean;

        //遍历查询是否有符合该sn的sku详情
        scanSkuDetailBeans.clear();
        selectedDetailbean = null;
        int index = 0;
        for (ScanReceiveShowDetailBean bean : detailBeans) {
            if (bean.getSkuid().equals(scanSnResponsebean.getSku()) &&
                    bean.getOwnerid().equals(scanSnResponsebean.getOwner())) {
                scanSkuDetailBeans.add(bean);
                selectedDetailbean = bean;
                break;
            }
            index++;
        }

        if (selectedDetailbean != null) {
            et_owner.setText(selectedDetailbean.getOwnername());
            boolean skuSingle = false;
            switch (getSnType(selectedDetailbean)) {
                case "ALL":
                    // 全程
                    if ("采购入库".equals(typein)) {
                        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "全程唯一码请扫描商品条码！", true, false);
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                        return;
                    } else {
                        // 逐条更新
                        skuSingle = true;
                    }
                    break;
                case "OFF":
                case "HALF":
                    SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "半程唯一码请商品条码！", true, false);
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                    selectedDetailbean = null;
                    return;
                default:
                    SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "商品唯一码类型不存在！", true, false);
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                    selectedDetailbean = null;
                    return;
            }
            Set<SnlistBean> snlistBeans = detailBeans.get(index).getSnlist();
            for (SnlistBean bean : snlistBeans) {
                if (bean.getSn().equals(et_skuCode.getText().toString())) {
                    SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "重复扫码序列号！", true, false);
                    CommonUtil.requestFocusAndClearText(et_skuCode);
                    selectedDetailbean = null;
                    return;
                }
            }
            addData(isSingle || skuSingle);
            SnlistBean snlistBean =  new SnlistBean(responsebean.getId(), et_skuCode.getText().toString(), responsebean.getSku());
            detailBeans.get(index).getSnlist().add(snlistBean);
            reflushTextView();
        } else {//否则的话就是扫错了
            SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "商品条码/SN码扫描有误，请检查", true, false);
            selectedDetailbean = null;
            et_owner.setText("");
            reflushTextView();
            CommonUtil.requestFocusAndClearText(et_skuCode);
        }
    }

    @Override
    public void pdaSnScanFailed(String msg) {
        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, msg, true, false);
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    @Override
    public void pdaCollectNullSnSuccess(ScanSnResponsebean orderInfoBean) {
        if (orderInfoBean != null) {
            SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "序列号已存在", false, false);
            CommonUtil.requestFocusAndClearText(et_sn);
            return;
        }
        int index = 0;
        for (int i= 0; i < detailBeans.size(); i++) {
            if (detailBeans.get(i).getSkuid().equals(selectedDetailbean.getSkuid())) {
                index = i;
                for (SnlistBean sn: detailBeans.get(i).getSnlist()) {
                    if (sn.getSn().equals(et_sn.getText().toString())) {
                        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "此SN已扫描！", true, false);
                        et_sn_view.setVisibility(View.GONE);
                        et_sn.setText("");
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                        return;
                    }
                }
                break;
            }
        }

        addData(true);
        SnlistBean snlistBean =  new SnlistBean("0", et_sn.getText().toString(), et_skuCode.getText().toString());
        detailBeans.get(index).getSnlist().add(snlistBean);
        // 置空
        et_sn_view.setVisibility(View.GONE);
        et_sn.setText("");
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    @Override
    public void pdaCollectNullSnFailed(String msg) {
        SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, msg, false, false);
        CommonUtil.requestFocusAndClearText(et_sn);
    }

    @Override
    public void confirmReceiptResult(boolean isSuccess, String msg) {
        if (isSuccess) {
            SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, "确认收货成功！", true, true);
            finish();
        } else {
            SpeakUtils.speakWithToast(ScanReceiveOperationActivity.this, msg, true, false);
        }
    }
}
